/**
 * 
 */
package ac.svn.accesscontrol.controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Set;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import ac.notification.event.INotificationListener;
import ac.notification.event.NotificationEvent;
import ac.svn.accesscontrol.manager.SVNInfoManager;
import ac.svn.accesscontrol.store.IResources;
import ac.svn.accesscontrol.store.ISVNIdentifier;
import ac.svn.accesscontrol.store.ISVNItem;
import ac.svn.accesscontrol.store.SVNGroup;
import ac.svn.accesscontrol.store.SVNUser;
import ac.svn.accesscontrol.ui.IUIConstants;
import ac.svn.accesscontrol.ui.UIComponentLibrary;
import ac.svn.accesscontrol.ui.helper.AccessRightsLister;
import ac.svn.accesscontrol.ui.helper.ToolbarTitleChangeListener;
import ac.svn.accesscontrol.ui.model.GroupListModel;
import ac.svn.accesscontrol.ui.model.UserListModel;
import ac.svn.accesscontrol.ui.renderer.SimpleIconRenderer;
import ac.svn.accesscontrol.ui.window.UserInfoWindow;
import ac.svn.accesscontrol.utils.Utility;

/**
 * @author Ankush
 *
 */
public class UserInfoController implements INotificationListener,IUIConstants,ISVNIdentifier {

	
	public static String TOOLBAR_TITLE = "Quick Operations";
	private long lastKeyType = 0;
	private String searchText = "";
	private boolean groupDisplayed = false;
	private UserInfoWindow userInfoWindow;
	private JButton userInfoBtn, groupInfoBtn;
	private JList itemList;
	private AccessRightsLister accessRightsLister;
	private JTextField textSearchField;
	private JLabel lblItemCount;

	public UserInfoController()
	{
		initComponents();
		registerListener();

	}

	private void registerListener() {
		userInfoBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				showUserEditor();
			}	
		});	

		groupInfoBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				showGroupEditor();
			}	
		});	

		userInfoWindow.addWindowListener(new WindowAdapter( ) {
			@Override
			public void windowClosing(WindowEvent e) {
				userInfoWindow.setVisible(false);
			}
		});

		itemList.addListSelectionListener(new ListSelectionListener() {

			@Override
			public void valueChanged(ListSelectionEvent e) {
				if(!e.getValueIsAdjusting())
				{
					ISVNItem item = (ISVNItem) itemList.getSelectedValue();
					if(null == item)
					{
						return;
					}

					if(item instanceof SVNGroup)
					{
						SVNGroup group = (SVNGroup) item;
						accessRightsLister.setGroup(true);
						accessRightsLister.listAccessRights(group.getGroupAlias());
					}
					else if(item instanceof SVNUser)
					{
						SVNUser user = (SVNUser) item;
						accessRightsLister.setGroup(false);
						accessRightsLister.listAccessRights(user.getUserAlias());
					}
				}
			}
		});

		textSearchField.addKeyListener(new KeyAdapter() {

			@Override
			public void keyReleased(KeyEvent e) {
				userInfoWindow.findText(textSearchField.getText());
			}
		});
		userInfoWindow.getRootPane().registerKeyboardAction(new ActionListener() 
		{
			@Override
			public void actionPerformed(ActionEvent e) {
				textSearchField.requestFocus();
			}
		}, KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);

		userInfoWindow.getRootPane().registerKeyboardAction(new ActionListener() 
		{
			@Override
			public void actionPerformed(ActionEvent e) {
				userInfoWindow.setVisible(false);
			}
		}, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);

		userInfoWindow.getRootPane().registerKeyboardAction(new ActionListener() 
		{
			@Override
			public void actionPerformed(ActionEvent e) {
				JLabel label = (JLabel) UIComponentLibrary.getComponent(UserInfoWindow.ExportedComponents.C_LABEL_INDEX_SEARCH);
				label.setText(" Type now.. ");
				itemList.requestFocus();
			}
		}, KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);

		itemList.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				long curTime = System.currentTimeMillis();
				int keyCode = e.getKeyCode();
				System.err.println(String.valueOf(keyCode));
				if((keyCode > 47 && keyCode < 58)
						||(keyCode > 64 && keyCode < 91))
				{
					if((curTime - lastKeyType) > 500)
					{
						searchText = String.valueOf(e.getKeyChar());
					}
					else
					{
						searchText += String.valueOf(e.getKeyChar());
					}
					JLabel label = (JLabel) UIComponentLibrary.getComponent(UserInfoWindow.ExportedComponents.C_LABEL_INDEX_SEARCH);
					label.setText(" Searching Text: " + searchText + " ");


					JList list = (JList) UIComponentLibrary.getComponent(UserInfoWindow.ExportedComponents.C_ITEM_LIST_VIEW);
					int searchedIndex = 0;
					if(groupDisplayed)
					{
						GroupListModel model = (GroupListModel) UIComponentLibrary.getComponent(UserInfoWindow.ExportedComponents.C_MODEL_GROUP_LIST);
						searchedIndex = model.indexOf(searchText);
					}
					else
					{
						UserListModel model = (UserListModel) UIComponentLibrary.getComponent(UserInfoWindow.ExportedComponents.C_MODEL_USER_LIST);
						searchedIndex = model.indexOf(searchText);
					}
					list.setSelectedIndex(searchedIndex);
					list.ensureIndexIsVisible(searchedIndex);
				}
				lastKeyType = System.currentTimeMillis();
			}

		});
	}

	private void initComponents() {
		userInfoWindow = new UserInfoWindow();

		JToolBar toolBar = (JToolBar) UIComponentLibrary.getComponent(C_TOOL_BAR);

		userInfoBtn = new JButton(Utility.getImageIcon(IResources.LOC_ICN_USER));
		userInfoBtn.setContentAreaFilled(false);
		userInfoBtn.setOpaque(false);
		//userInfoBtn.setIcon(new CompoundIcon(Axis.Y_AXIS, 2,(Utility.getImageIcon(IResources.LOC_ICN_USER)), (new TextIcon(userInfoBtn,"User Report"))));
		userInfoBtn.setToolTipText("User report.");
		userInfoBtn.addMouseListener(new ToolbarTitleChangeListener(TOOLBAR_TITLE, "Shows User summary!"));


		groupInfoBtn = new JButton(Utility.getImageIcon(IResources.LOC_ICN_GROUP));
		groupInfoBtn.setContentAreaFilled(false);
		groupInfoBtn.setOpaque(false);
		//groupInfoBtn.setIcon(new CompoundIcon(Axis.Y_AXIS, 2,(Utility.getImageIcon(IResources.LOC_ICN_GROUP)), (new TextIcon(groupInfoBtn,"Group Report"))));
		groupInfoBtn.setToolTipText("Group report.");
		groupInfoBtn.addMouseListener(new ToolbarTitleChangeListener(TOOLBAR_TITLE, "Shows Group summary!"));

		//JLabel search = new JLabel("Search User:");
		textSearchField = (JTextField) UIComponentLibrary.getComponent(UserInfoWindow.ExportedComponents.C_TEXT_SEARCH);

		itemList = (JList) UIComponentLibrary.getComponent(UserInfoWindow.ExportedComponents.C_ITEM_LIST_VIEW);
		accessRightsLister = new AccessRightsLister(UserInfoWindow.ExportedComponents.C_TEXT_PANE_DETAILS);
		accessRightsLister.setClearRequired(true);

		lblItemCount = (JLabel) UIComponentLibrary.getComponent(UserInfoWindow.ExportedComponents.C_TEXT_ITEM_COUNT);

		//toolBar.add(userInfoBtn);
		toolBar.addSeparator();
		//toolBar.add(groupInfoBtn);
		toolBar.addSeparator();
	}


	private void showGroupEditor()
	{
		groupDisplayed = true;
		JList list = (JList) UIComponentLibrary.getComponent(UserInfoWindow.ExportedComponents.C_ITEM_LIST_VIEW);
		list.setCellRenderer(new SimpleIconRenderer("images/group.png"));
		GroupListModel model = (GroupListModel) UIComponentLibrary.getComponent(UserInfoWindow.ExportedComponents.C_MODEL_GROUP_LIST);
		model.clearList();
		model.addGroups(SVNInfoManager.getInfoManager().getAllGroups());
		lblItemCount.setText("Groups: " + String.valueOf(model.getSize()));
		list.setModel(model);
		userInfoWindow.setVisible(true);
	}

	private void showUserEditor()
	{
		groupDisplayed = false;
		JList list = (JList) UIComponentLibrary.getComponent(UserInfoWindow.ExportedComponents.C_ITEM_LIST_VIEW);
		list.setCellRenderer(new SimpleIconRenderer("images/user.png"));
		UserListModel model = (UserListModel) UIComponentLibrary.getComponent(UserInfoWindow.ExportedComponents.C_MODEL_USER_LIST);
		model.clearList();
		model.addUsers(SVNInfoManager.getInfoManager().getAllUsers());
		lblItemCount.setText("Users: " + String.valueOf(model.getSize()));
		list.setModel(model);
		userInfoWindow.setVisible(true);
	}




	@Override
	public Set<String> declaredSubscriptionSet() {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public void receiveEvent(NotificationEvent arg0) {
		// TODO Auto-generated method stub

	}

}
